﻿using Enter.Admin.Enums;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Linq;

namespace Enter.Admin.Utils
{
    public class Jsons
    {
        public static string Serialize<T>(T data)
        {
            //var setting = new JsonSerializerSettings
            //{
            //    ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            //};
            return Newtonsoft.Json.JsonConvert.SerializeObject(data);
            //return System.Text.Json.JsonSerializer.Serialize(data);
        }

        public static T Deserialize<T>(string value)
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(value);
            //return System.Text.Json.JsonSerializer.Deserialize<T>(value);
        }
    }

    public class DateFormatConverter : IsoDateTimeConverter
    {
        public const string Format_yyyyMMddHHmmss = "yyyy-MM-dd HH:mm:ss";
        public const string Format_yyyyMMdd = "yyyy-MM-dd";
        public DateFormatConverter()
        {
            base.DateTimeFormat = Format_yyyyMMdd;
        }
        public DateFormatConverter(string format)
        {
            base.DateTimeFormat = format;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value == null || (DateTime)value == DateTime.MinValue)
            {
                writer.WriteValue(string.Empty);
            }
            else
            {
                base.WriteJson(writer,value, serializer);
            }
        }
    }

    public class EnumConverter : StringEnumConverter
    {
        private string EnumName { get; set; } = string.Empty;
        public EnumConverter()
        {
        }
        public EnumConverter(string enumName)
        {
            EnumName = enumName;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            
            if (value == null || value.ToString() == "0" || string.IsNullOrWhiteSpace(value.ToString()))
            {
                writer.WriteValue(string.Empty);
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(EnumName))
                {
                    EnumsExt.EnumMap.TryGetValue(EnumName, out var listItems);
                    if (listItems != null)
                    {
                        var item = listItems.Where(t => t.Value == value.ToString() || t.Text == value.ToString()).FirstOrDefault();
                        if (item != null)
                        {
                            writer.WriteValue(item.Text);
                        }
                        return;
                    }
                    writer.WriteValue(string.Empty);
                    return;
                }
                base.WriteJson(writer, value, serializer);
            }
        }
    }

    

}
